package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.TabExpander;

import com.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.common.CheckAdminToken;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;

import jodd.util.StringUtil;

//token验证拦截器 使用前注意需要一个@Bean手动注解，否则注入无效
public class AdminTokenInterceptor implements HandlerInterceptor {
    @Autowired
    CheckAdminToken checkAdminToken;
    @Autowired
    SystemAdminService systemAdminService;

    //程序处理之前需要处理的业务
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String token = checkAdminToken.getTokenFormRequest(request);
        
        if(token == null || token.isEmpty()){
        	// 拼多多授权页面单独无需登陆
        	String servletPath = request.getRequestURI();
    		if(StringUtils.isNotBlank(request.getParameter("state")) && servletPath.contains(Constants.NOTIFY_PDD_AUTH_TOKEN)) {
    			return true;
    		}

            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        
        Boolean result = checkAdminToken.check(token);
        if(!result){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        String identification = request.getHeader(Constants.IDENTIFICATION);
        if(StringUtil.isNotBlank(identification) && "APP".equalsIgnoreCase(identification)) {
            return true;
        }
        
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        if(!token.equals(systemAdmin.getNowToken())) {
        	response.getWriter().write(JSONObject.toJSONString(CommonResult.exitError()));
        	return false;
        }
        
        return true;
    }

    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) {

    }

}
